use std::sync::{Arc, Condvar, Mutex};
use std::thread;

fn main() {
    // Mutex Condvar
    let mutex = Arc::new(Mutex::new(false));
    let condvar = Arc::new(Condvar::new());
    //创建多线程
    let mut handles = vec![];
    for id in 0..3 {
        let mutex = Arc::clone(&mutex);
        let condvar = Arc::clone(&condvar);
        let handle = thread::spawn(move || {
            // Mutex锁
            let mut guard = mutex.lock().unwrap();
            //等待条件为 true
            while !*guard {
                guard = condvar.wait(guard).unwrap();
            }
            //条件满足后执行的操作
            println!("Thread {} woke up", id);
        });
        handles.push(handle);
    }

    //模拟条件后唤醒等待的线程
    thread::sleep(std::time::Duration::from_secs(2));
    //修改条件，唤醒等待的线程
    {
        let mut guard = mutex.lock().unwrap();
        *guard = true;
        condvar.notify_all();
    }

    //等待写入线程完成
    for handle in handles {
        handle.join().unwrap();
    }
}
